//
//  SendPictureViewController.m
//  u76ho
//
//  Created by m-air-01 on 16/1/12.
//  Copyright © 2016年 LV. All rights reserved.
//

#import "SendPictureViewController.h"
#import "SendPictureTableViewCell.h"
#import "PicAlumeTableViewCell.h"
#import "WhoCanSeeViewController.h"
#import "LocationViewController.h"
#import "ZYQAssetPickerController.h"
#import "DistubuteInfoModel.h"

#import "PhotoBroswerVC.h"
#import "PhotoCotentView.h"
#import "DeleteImgViewController.h"
@interface SendPictureViewController ()
<UITableViewDataSource,UITableViewDelegate,ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate,UITextViewDelegate,LocationDelegate,WhoCanSeeDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,DeleteImgViewDelegate,UIAlertViewDelegate>
{
    UITableView * _tableView;
    UITableView * _picAlumeTableView;//选图集
    NSMutableArray * _picAlumeArr;
    
    NSMutableArray * myPictureArr;//选择照片数组
    CGFloat firstViewHeight;
    
    DistubuteInfoModel * distubuteinfomodel;
    UIButton * sendBtn;
    
    NSString * alumId;
    NSMutableArray * picStrArr;
    NSMutableArray * imgsizeStrArr;
    
    UIImagePickerController * _pickerVC;
    
}
@end
static BOOL or = YES;

@implementation SendPictureViewController
#pragma mark - 视图的生命周期
-(void)viewDidAppear:(BOOL)animated
{
    
    [super viewDidAppear:YES];

    self.navigationController.navigationBarHidden = NO;
    if (_sendPicture == YES) {
        ZYQAssetPickerController * picker = [[ZYQAssetPickerController alloc]init];
        picker.maximumNumberOfSelection = 8;
        picker.assetsFilter = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups=NO;
        picker.delegate=self;
        picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                return duration >= 5;
            } else {
                return YES;
            }
        }];
        
        [self presentViewController:picker animated:YES completion:nil];
        self.view.backgroundColor = [UIColor whiteColor];
        [self performSelector:@selector(main) withObject:nil afterDelay:1];
    }

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (_sendPicture == YES) {
        
        alumId = @"";
        distubuteinfomodel = [[DistubuteInfoModel alloc]init];
        distubuteinfomodel.content = @"";
        distubuteinfomodel.pic = @"";
        distubuteinfomodel.imgsize = @"";
        distubuteinfomodel.position = @"";
        distubuteinfomodel.isopen = @"1";
        distubuteinfomodel.codes = @"";
        distubuteinfomodel.type = alumId;

        
    }
    else
    {
        alumId = @"";
        distubuteinfomodel = [[DistubuteInfoModel alloc]init];
        distubuteinfomodel.content = @"";
        distubuteinfomodel.pic = @"";
        distubuteinfomodel.imgsize = @"";
        distubuteinfomodel.position = @"";
        distubuteinfomodel.isopen = @"1";
        distubuteinfomodel.codes = @"";
        distubuteinfomodel.type = alumId;
        [self main];
    }
    [self addItems];
    // Do any additional setup after loading the view.
}
-(void)main
{
    [self addRight];
    
    if (_sendPicture == YES) {
        self.navigationItem.title = @"发布图片";
    }
    else
    {
        self.navigationItem.title= @"发布文字";
    }

    
    _sendPicture = NO;
    myPictureArr = [[NSMutableArray alloc]init];
    if (_img != nil) {
        [myPictureArr addObject:_img];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createAlumeNotificase:) name:@"createAlumeNotificase" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SearchLocationNoti:) name:@"SearchLocationNoti" object:nil];
    
    _picAlumeArr = [[NSMutableArray alloc]init];
    
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource =self;
    _tableView.tag = 504;
    [_tableView registerNib:[UINib nibWithNibName:@"SendPictureTableViewCell" bundle:nil] forCellReuseIdentifier:@"SendPictureTableViewCell"];
    _tableView.tableHeaderView = [self createHeaderView];
    [self.view addSubview:_tableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self requestAlum];
}
-(void)sendPictureData
{
    picStrArr = [[NSMutableArray alloc]init];;
    imgsizeStrArr = [[NSMutableArray alloc]init];;
    
    for (int i = 0; i<myPictureArr.count; i++) {
        UIImage *tempImg=myPictureArr[i];
        __weak typeof(self)weakSelf = self;
        
        
        NSDate * date = [NSDate date];
        NSInteger dataCH = [date timeIntervalSince1970];
        NSString * dateStr = [NSString stringWithFormat:@"%i",(int)dataCH];
        
        int randanNum = arc4random() % 1000000;
        NSString * tempStr = [NSString stringWithFormat:@"%@%i.jpg",dateStr,randanNum];
        
        [U76HONet upPictureWithaction:@"" pictures:@[tempImg] picname:tempStr andDataBlock:^(NSDictionary *dic) {
            NSLog(@"上穿图片成功了");
        
            [imgsizeStrArr addObject:[dic objectForKey:@"data"]];
            [picStrArr addObject:tempStr];
            
            if (imgsizeStrArr.count == myPictureArr.count) {
                distubuteinfomodel.imgsize = [imgsizeStrArr componentsJoinedByString:@"|"];
                distubuteinfomodel.pic = [picStrArr componentsJoinedByString:@"|"];

//                [weakSelf distubteInformation];
                
                [U76HONet infomationSendWithAction:@"" code:[Singleton share].code Type:distubuteinfomodel.type Qycode:[Singleton share].yqcode Content:distubuteinfomodel.content ? distubuteinfomodel.content : @"" Pic:distubuteinfomodel.pic imgsize:distubuteinfomodel.imgsize Position:distubuteinfomodel.position Isopen:distubuteinfomodel.isopen Codes:distubuteinfomodel.codes andDataBlock:^(NSDictionary *dic) {
                    NSLog(@"发布信息成功了");
                    [Singleton alerSendMessage:@"发布成功"];
                    if (_isNeedRefresh == YES) {
                        _refreshBlock();
                    }
                    [weakSelf performSelector:@selector(backItem:) withObject:nil afterDelay:1.0];
                }];

            }
            
        }];

    }
}
-(void)distubteInformation
{
    __weak typeof(self)weakSelf = self;
    if (![distubuteinfomodel.content isEqualToString:@""]) {
        [U76HONet infomationSendWithAction:@"" code:[Singleton share].code Type:distubuteinfomodel.type Qycode:[Singleton share].yqcode Content:distubuteinfomodel.content Pic:distubuteinfomodel.pic imgsize:distubuteinfomodel.imgsize Position:distubuteinfomodel.position Isopen:distubuteinfomodel.isopen Codes:distubuteinfomodel.codes andDataBlock:^(NSDictionary *dic) {
            NSLog(@"发布信息成功了");
            [Singleton alerSendMessage:@"发布成功"];
            if (_isNeedRefresh == YES) {
                _refreshBlock();
            }
            [weakSelf performSelector:@selector(backItem:) withObject:nil afterDelay:1.0];

        }];
        
    }
    else
    {
        [Singleton alerSendMessage:@"内容不能为空"];
    }

    
}
-(void)backItem:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
[self dismissViewControllerAnimated:YES completion:nil];
}

//获取相册的信息
-(void)requestAlum
{
    
    
    [U76HONet selectedTypeReadWithtype:@"9" fid:@"0" code:[Singleton share].code andDataBlock:^(NSArray *arr) {
        NSLog(@"获取相册的内容成功了");
        if (arr.count!=0) {
            UIButton * btn = (UIButton *)[self.view viewWithTag:300];
            PositionModel * model = arr.firstObject;
            alumId = model.Ids;
            [btn setTitle:model.typenames forState:UIControlStateNormal];
        }
        if (_picAlumeArr.count!=0) {
            [_picAlumeArr removeAllObjects];
        }
        [_picAlumeArr addObjectsFromArray:arr];
        NSLog(@"********%i",(int)_picAlumeArr.count);
        [_picAlumeTableView reloadData];
    }];
}
//创建相册
-(void)createAlumWithname:(NSString *)name
{
    __weak typeof(self)weakSelf = self;
    [U76HONet createAlumWithaction:@"" code:[Singleton share].code name:name andDataBlock:^(NSDictionary *dic) {
        NSLog(@"创建相册成功了");
        [weakSelf requestAlum];
        [weakSelf performSelector:@selector(alertV) withObject:nil afterDelay:1.0];
    }];
}

#pragma mark - _tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 504) {
        return 2;
    }
    return _picAlumeArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 504) {
        SendPictureTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SendPictureTableViewCell"];
        if (indexPath.row == 0) {
            cell.firstLab.text = @"所在位置";
            cell.secondLab.tag = 556;
        }
        else
        {
            cell.firstLab.text = @"谁可以看";
            cell.secondLab.text = @"公开";
            cell.secondLab.tag = 555;
        }
        return cell;
    }
    else
    {
        PicAlumeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"PicAlumeTableViewCell"];
        cell.model = _picAlumeArr[indexPath.row];
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 504) {
        if (indexPath.row == 0) {
            LocationViewController * locationVC = [[LocationViewController alloc]init];
            locationVC.delegate = self;
            [self.navigationController pushViewController:locationVC animated:YES];
        }
        else
        {
            WhoCanSeeViewController * whocanSeeVC = [[WhoCanSeeViewController alloc]init];
            whocanSeeVC.delegate = self;
            [self.navigationController pushViewController:whocanSeeVC animated:YES];
        }
    }
    else
    {
        UIButton * btn = (UIButton *)[self.view viewWithTag:300];
        PositionModel * model = _picAlumeArr[indexPath.row];
        alumId = model.Ids;
        distubuteinfomodel.type = model.Ids;
        [btn setTitle:model.typenames forState:UIControlStateNormal];
        
        
        UIView * mengBanV = (UIView *)[self.view viewWithTag:557];
        mengBanV.hidden = YES;
        _picAlumeTableView.hidden = YES;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 504) {
        return 50;
    }
    return 30;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 504) {
        return SIZETO6H(20);
    }
    return 1;
}
//-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section
//{
//    return SCREEN_HEIGHT;
//}
#pragma mark - createHeaderView
-(UIView *)createHeaderView
{
    CGFloat picWidth = (SCREEN_WIDTH - SIZETO6W(20)*2 - SIZETO6W(10)*3)/4;
    
    //第一个view
    UIView * view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100+SIZETO6H(20)*2)];
    view1.tag = 401;
    view1.backgroundColor = [UIColor whiteColor];
    //textView
    UITextView * textView = [[UITextView alloc]initWithFrame:CGRectMake(SIZETO6W(20), SIZETO6H(20), SCREEN_WIDTH-SIZETO6W(20)*2, view1.height-SIZETO6H(20)*2)];
    textView.tag = 712;
    textView.font = [UIFont systemFontOfSize:18];
    textView.delegate = self;
    [view1 addSubview:textView];
    
    UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(SIZETO6W(25), SIZETO6H(30), 120 , 20)];
    lab.text = @"这一刻的想法...";
    lab.textColor = [UIColor lightGrayColor];
    lab.tag = 713;
    [view1 addSubview:lab];
    
    //第二个view
    UIView * view2 = [[UIView alloc]initWithFrame:CGRectMake(0, view1.bottom, SCREEN_WIDTH, picWidth+SIZETO6H(10))];
    view2.tag = 402;
    view2.backgroundColor = [UIColor whiteColor];
    
    //添加图片按钮
    UIButton * addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.tag = 403;
    if (myPictureArr.count!=0) {
        UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(SIZETO6W(20), 0, picWidth, picWidth)];
        imgV.image = myPictureArr.firstObject;
        [view2 addSubview:imgV];
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        imgV.tag = myPictureArr.count + 1;
        imgV.userInteractionEnabled = YES;
        imgV.userInteractionEnabled = YES;
        [imgV addGestureRecognizer:tap];
        addBtn.frame = CGRectMake(imgV.right + SIZETO6W(10), 0, picWidth, picWidth);
    }
    else
    {
        addBtn.frame = CGRectMake(SIZETO6W(20), 0, picWidth, picWidth);
    }
    [addBtn setImage:[UIImage imageNamed:@"添加图片图标"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addPictureAction:) forControlEvents:UIControlEventTouchUpInside];
//    if (_sendPicture == YES) {
//        [self addPictureAction:addBtn];
//    }
    addBtn.layer.masksToBounds = YES;
    addBtn.layer.borderColor = [UIColorFromRGB(0xc0c5ce) CGColor];
    addBtn.layer.borderWidth = 1.0f;
    [view2 addSubview:addBtn];
    //分割线
    UIView * lineV = [[UIView alloc]initWithFrame:CGRectMake(SIZETO6W(20), view2.height-1, SCREEN_WIDTH-SIZETO6W(20), 1)];
    lineV.tag = 404;
    lineV.backgroundColor = UIColorFromRGB(0xc0c5ce);
    [view2 addSubview:lineV];
    
    //第三个view
    UIView * view3 = [[UIView alloc]initWithFrame:CGRectMake(0, view2.bottom, SCREEN_WIDTH, 50)];
    view3.tag = 405;
    view3.backgroundColor = [UIColor whiteColor];
    //同步到我的图集
    UIButton * tongbuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    tongbuBtn.frame = CGRectMake(SIZETO6W(20), (view3.frame.size.height-30)/2, 30, 30);
    [tongbuBtn setImage:[UIImage imageNamed:@"同步图集-未选中"] forState:UIControlStateNormal];
    [tongbuBtn setImage:[UIImage imageNamed:@"选中图标"] forState:UIControlStateSelected];
    [tongbuBtn addTarget:self action:@selector(tongbuBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [view3 addSubview:tongbuBtn];
    UILabel * tongbuLab = [[UILabel alloc]initWithFrame:CGRectMake(tongbuBtn.right, 0, 120, view3.height)];
    tongbuLab.text = @"同步到我的图集";
    tongbuLab.font = [UIFont systemFontOfSize:15];
    tongbuLab.textColor = UIColorFromRGB(0x333944);
    tongbuLab.textAlignment = NSTextAlignmentCenter;
    [view3 addSubview:tongbuLab];
    //工作图片
    UIButton * selectedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    selectedBtn.frame = CGRectMake(tongbuLab.right, (view3.frame.size.height-30)/2, 80, 30);
//    [selectedBtn setTitle:@"工作图片" forState:UIControlStateNormal];
    selectedBtn.tag = 300;
    [selectedBtn addTarget:self action:@selector(selecteAlumeAction:) forControlEvents:UIControlEventTouchUpInside];
    [selectedBtn setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
    selectedBtn.titleLabel.font = [UIFont systemFontOfSize:13];
//    [selectedBtn setImage:[UIImage imageNamed:@"图集展开案"] forState:UIControlStateNormal];
    UIImageView * zhankaiImgV = [[UIImageView alloc]initWithFrame:CGRectMake(selectedBtn.width - 11 - 5, (selectedBtn.height - 6)/2, 11, 6)];
    zhankaiImgV.image = [UIImage imageNamed:@"图集展开案"];
    [selectedBtn addSubview:zhankaiImgV];
//    selectedBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 55, 0, -55);
//    UIKIT_STATIC_INLINE UIEdgeInsets UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) {

    selectedBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 16);
    
    selectedBtn.layer.masksToBounds = YES;
    selectedBtn.layer.borderColor = [UIColorFromRGB(0xc0c5ce) CGColor];
    selectedBtn.layer.borderWidth = 1.0f;
    selectedBtn.layer.cornerRadius = 5;
    [view3 addSubview:selectedBtn];
    //新建图集
    UIButton * newBuildBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    newBuildBtn.frame = CGRectMake(selectedBtn.right, (view3.frame.size.height-30)/2, 80, 30);
    [newBuildBtn setTitle:@"新建图集" forState:UIControlStateNormal];
    [newBuildBtn addTarget:self action:@selector(newBuildBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    newBuildBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [newBuildBtn setTitleColor:UIColorFromRGB(0x6ec844) forState:UIControlStateNormal];
    [view3 addSubview:newBuildBtn];
    
    
    //总view
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, view3.height+view2.height+view1.height)];
    firstViewHeight = view.height;
    view.tag = 512;
    [self.view addSubview:view];
    [view addSubview:view1];
    [view addSubview:view2];
    [view addSubview:view3];
    
    
    return view;
}
#pragma mark - UIButton的点击事件   添加图片
-(void)addPictureAction:(UIButton *)btn
{
    
    
    
    //[self.view resignFirstResponder];
    
    UITextView * textView = (UITextView *)[self.view viewWithTag:712];
    [textView resignFirstResponder];
    UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
    [sheet showInView:self.view];
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        _pickerVC = [[UIImagePickerController alloc]init];
        [_pickerVC setSourceType:UIImagePickerControllerSourceTypeCamera];
        _pickerVC.delegate = self;
        [self presentViewController:_pickerVC animated:YES completion:nil];
    }
    else if (buttonIndex == 1)
    {
        ZYQAssetPickerController * picker = [[ZYQAssetPickerController alloc]init];
        picker.maximumNumberOfSelection = 8-myPictureArr.count;
        picker.assetsFilter = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups=NO;
        picker.delegate=self;
        picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                return duration >= 5;
            } else {
                return YES;
            }
        }];
        
        [self presentViewController:picker animated:YES completion:NULL];
        
    }
}
//将选中的图片付给头像
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage * selecImg = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [myPictureArr addObject:selecImg];
    [self refreshImgView];
}
-(void)newBuildBtnAction:(UIButton *)btn
{
    [Singleton alercreateAlumeMessage:@"新建图集" content:@"请为此相册输入名称" btnName:@"确定"];
}
-(void)tongbuBtnAction:(UIButton *)btn
{
    
    if (_picAlumeArr.count == 0) {
        [Singleton alerSendMessage:@"相册为空"];
    }
    else
    {
        if (btn.selected == NO) {
            btn.selected = YES;
            distubuteinfomodel.type = alumId;
        }
        else
        {
            btn.selected = NO;
            distubuteinfomodel.type = @"";
        }
        
    }
}
-(void)selecteAlumeAction:(UIButton *)btn
{

//    UIView * mengBanView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
//    mengBanView.backgroundColor = [UIColor blackColor];
//    mengBanView.alpha = 0.5;
//    mengBanView.userInteractionEnabled = YES;
//    [RootWindow addSubview:mengBanView];
//    
//    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissAction:)];
//    tap.numberOfTapsRequired = 1;
//    tap.numberOfTouchesRequired = 1;
//    [mengBanView addGestureRecognizer:tap];
    
    
    UIView * view = (UIView *)[self.view viewWithTag:512];
    CGFloat left = 150 + SIZETO6W(20);
    if (_picAlumeTableView) {
        
    }
    else
    {
        
        //下拉选图集按钮
        _picAlumeTableView = [[UITableView alloc]initWithFrame:CGRectMake(left, view.height+64, 120, 0) style:UITableViewStyleGrouped];
        _picAlumeTableView.dataSource = self;
        _picAlumeTableView.delegate = self;
        _picAlumeTableView.layer.masksToBounds = YES;
        _picAlumeTableView.layer.borderColor = [UIColorFromRGB(0x94999f) CGColor];
        _picAlumeTableView.layer.borderWidth = 1.0f;
        _picAlumeTableView.layer.cornerRadius = 6;
        [_picAlumeTableView registerNib:[UINib nibWithNibName:@"PicAlumeTableViewCell" bundle:nil] forCellReuseIdentifier:@"PicAlumeTableViewCell"];
        UIView * mengbanView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
        mengbanView.userInteractionEnabled = YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mengBanTapAction:)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        [mengbanView addGestureRecognizer:tap];
        mengbanView.backgroundColor = [UIColor clearColor];
        mengbanView.tag = 557;
        [self.view addSubview:mengbanView];
        [self.view addSubview:_picAlumeTableView];
        _picAlumeTableView.hidden = NO;

        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    UIView * mengbanV = (UIView *)[self.view viewWithTag:557];
    mengbanV.backgroundColor = [UIColor clearColor];
    if (or == YES) {
        or = NO;
        mengbanV.hidden = NO;
        _picAlumeTableView.hidden = NO;
        if (_picAlumeArr.count == 1) {
            _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 30);
        }
        else if (_picAlumeArr.count == 2)
        {
            _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 60);
        }
        else
        {
            _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 90);
        }

        [UIView animateWithDuration:0.3 animations:^{
            if (_picAlumeArr.count == 1) {
                _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 30);
            }
            else if (_picAlumeArr.count == 2)
            {
                _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 60);
            }
            else
            {
                _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 90);
            }
        } completion:nil];
    }
    else
    {
        or = YES;
        mengbanV.hidden = NO;
        if (_picAlumeArr.count == 1) {
            _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 30);
        }
        else if (_picAlumeArr.count == 2)
        {
            _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 60);
        }
        else
        {
            _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 90);
        }
        _picAlumeTableView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            if (_picAlumeArr.count == 1) {
                _picAlumeTableView.frame = CGRectMake(left, view.height+64 , 120, 30);
            }
            else if (_picAlumeArr.count == 2)
            {
                _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 60);
            }
            else
            {
                _picAlumeTableView.frame = CGRectMake(left, view.height+64, 120, 90);
            }        } completion:^(BOOL finished) {
            
        }];
    }
}
-(void)mengBanTapAction:(UITapGestureRecognizer *)tap
{
    UIView * mengBanV = (UIView *)tap.view;
    mengBanV.hidden = YES;
    _picAlumeTableView.hidden = YES;

}
#pragma mark - textViewDelegate
-(void)dismissAction:(UITapGestureRecognizer *)tap
{
    NSLog(@"tap");
    UIView * view = (UIView *)tap.view;
    [view removeFromSuperview];
}
#pragma mark - 消息通知的实现方法
-(void)createAlumeNotificase:(NSNotification *)noti
{
    NSLog(@"*********发布图片监听到了通知");
    NSLog(@"%@",noti.object);
    if (noti.object != nil) {
        [self createAlumWithname:noti.object];
    }
}
-(void)SearchLocationNoti:(NSNotification *)noti
{
    distubuteinfomodel.position = noti.object;
    UILabel * lab = (UILabel *)[self.view viewWithTag:556];
    lab.text = noti.object;
}
-(void)alertV
{
    [Singleton alerSendMessage:@"创建成功"];
}
#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    NSMutableArray * mArr = [[NSMutableArray alloc]init];
    for (int i = 0; i<assets.count; i++) {
        ALAsset *asset=assets[i];
        UIImage *tempImg=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [mArr addObject:tempImg];
    }
    [myPictureArr addObjectsFromArray:mArr];
    [self refreshImgView];
}
-(void)refreshImgView
{
    UIView * view = (UIView *)[self.view viewWithTag:512];
    view.backgroundColor = [UIColor whiteColor];
    int i;
    int j;
    if (myPictureArr.count!=8) {
        i = (int)((int)myPictureArr.count+1)/4;
        j = (int)((int)myPictureArr.count+1)%4;
    }
    else
    {
        i = (int)((int)myPictureArr.count)/4;
        j = (int)((int)myPictureArr.count)%4;
    }
    NSLog(@"********%iand%i",i,j);
    
    CGFloat picWidth = (SCREEN_WIDTH - SIZETO6W(20)*2 - SIZETO6W(10)*3)/4;
    
    int addHeight;
    if (i >= 1) {
        addHeight = (i-1)*(picWidth+SIZETO6H(10));
        if (j!=0) {
            addHeight+=picWidth+SIZETO6H(10);
        }
    }
    else
    {
        addHeight = 0;
    }
//    NSLog(@"=================================%i",(int)(firstViewHeight+addHeight));
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH, (int)((int)firstViewHeight+addHeight));
    //其它子控件的位置整体下移
    UIView * view1 = (UIView *)[self.view viewWithTag:401];
    
    UIView * view2 = (UIView *)[self.view viewWithTag:402];
    for (id i in view2.subviews) {
        if ([i isKindOfClass:[UIImageView class]]) {
            [i removeFromSuperview];
        }
    }
    view2.frame = CGRectMake(0, view1.bottom, SCREEN_WIDTH, (int)(picWidth+SIZETO6H(10) + (int)addHeight));
    view2.backgroundColor = [UIColor whiteColor];
    
    //九宫格设置图片
    
    if (myPictureArr.count == 8) {
        for (int i = 0; i<myPictureArr.count; i++) {
            int row = i/4;
            int loc = i%4;
            UIButton * addPicBtn = (UIButton *)[self.view viewWithTag:403];
            addPicBtn.enabled = NO;
            UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(SIZETO6W(20)+loc*(picWidth + SIZETO6H(10)), row*(picWidth+SIZETO6H(10)), picWidth, picWidth)];
            imgV.backgroundColor = [UIColor redColor];
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
            tap.numberOfTapsRequired = 1;
            tap.numberOfTouchesRequired = 1;
            imgV.tag = i + 1;
            imgV.userInteractionEnabled = YES;
            [imgV addGestureRecognizer:tap];
            UIImage *tempImg =myPictureArr[i];
            dispatch_async(dispatch_get_main_queue(), ^{
                float tempW = (tempImg.size.height - tempImg.size.width) >= 0 ? tempImg.size.width : tempImg.size.height;
                UIImage * tempImg2 = [tempImg croppedImageAtFrame:CGRectMake((tempImg.size.height - tempImg.size.width) >= 0 ? 0 : (tempImg.size.width - tempImg.size.height)/2, (tempImg.size.width - tempImg.size.height) >= 0 ? 0 : (tempImg.size.height - tempImg.size.width)/2 , tempW, tempW)];
                [imgV setImage:tempImg2];
            });
            
            [view2 addSubview:imgV];
        }
        
    }
    else
    {
        
        for (int i = 0; i<myPictureArr.count+1; i++) {
            int row = i/4;
            int loc = i%4;
            if (i == myPictureArr.count) {
                UIButton * addPicBtn = (UIButton *)[self.view viewWithTag:403];
                addPicBtn.enabled = YES;
                addPicBtn.frame = CGRectMake(SIZETO6W(20)+loc*(picWidth + SIZETO6H(10)), row*(picWidth+SIZETO6H(10)), picWidth, picWidth);
            }
            else
            {
                UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(SIZETO6W(20)+loc*(picWidth + SIZETO6H(10)), row*(picWidth+SIZETO6H(10)), picWidth, picWidth)];
                imgV.backgroundColor = [UIColor redColor];
                UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
                tap.numberOfTapsRequired = 1;
                tap.numberOfTouchesRequired = 1;
                imgV.tag = i + 1;
                imgV.userInteractionEnabled = YES;
                [imgV addGestureRecognizer:tap];
                UIImage *tempImg =myPictureArr[i];
                dispatch_async(dispatch_get_main_queue(), ^{
                    float tempW = (tempImg.size.height - tempImg.size.width) >= 0 ? tempImg.size.width : tempImg.size.height;
                    UIImage * tempImg2 = [tempImg croppedImageAtFrame:CGRectMake((tempImg.size.height - tempImg.size.width) >= 0 ? 0 : (tempImg.size.width - tempImg.size.height)/2, (tempImg.size.width - tempImg.size.height) >= 0 ? 0 : (tempImg.size.height - tempImg.size.width)/2 , tempW, tempW)];
                    [imgV setImage:tempImg2];
                });

                
                [view2 addSubview:imgV];
            }
        }
    }
    
    UIView * lineV = (UIView *)[self.view viewWithTag:404];
    NSLog(@"$$$$$$$$$$$$$$$$$$%i",(int)view2.height);
    lineV.frame = CGRectMake(SIZETO6W(20), view2.height-1, SCREEN_WIDTH-SIZETO6W(20), 1);
    
    UIView * view3 = (UIView *)[self.view viewWithTag:405];
    view3.frame = CGRectMake(0, view2.bottom, SCREEN_WIDTH, 50);
    NSLog(@"*********************%i",(int)view.height);
    _tableView.tableHeaderView = view;

}
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    NSLog(@"tapAction is did");
    int i = (int)tap.view.tag;
    DeleteImgViewController * deleteImgVVC = [[DeleteImgViewController alloc]init];
    deleteImgVVC.delegate = self;
    deleteImgVVC.i = i;
    deleteImgVVC.imgArr = myPictureArr;
    [self.navigationController pushViewController:deleteImgVVC animated:YES];
}
#pragma mark - deleteImgVdelegate
-(void)deleteFinishImgArr:(NSArray *)arr
{
    [myPictureArr removeAllObjects];
    [myPictureArr addObjectsFromArray:arr];
    [self refreshImgView];
}
#pragma mark - textViewDelegate
-(void)textViewDidChange:(UITextView *)textView
{
    distubuteinfomodel.content = textView.text;
    UILabel * lab = (UILabel *)[self.view viewWithTag:713];
    if ([textView.text isEqualToString:@""]) {
        lab.hidden = NO;
    }
    else
    {
        lab.hidden = YES;
    }
}
-(void)locationDelegateWithStr:(NSString *)str
{
    distubuteinfomodel.position = str;
    UILabel * lab = (UILabel *)[self.view viewWithTag:556];
    lab.text = str;
}
-(void)whocanseeDelegateWithtype:(NSString *)type codes:(NSString *)codes
{
    if ([type isEqualToString:@"1"]) {
        distubuteinfomodel.isopen = @"1";
        UILabel * lab = (UILabel *)[self.view viewWithTag:555];
        lab.text = @"公开";
        distubuteinfomodel.codes = codes;
    }
    else if ([type isEqualToString:@"2"])
    {
        distubuteinfomodel.isopen = @"2";
        UILabel * lab = (UILabel *)[self.view viewWithTag:555];
        lab.text = @"私密";
        distubuteinfomodel.codes = codes;
    }
    else
    {
        distubuteinfomodel.isopen = @"3";
        UILabel * lab = (UILabel *)[self.view viewWithTag:555];
        lab.text = @"部分可见";
        distubuteinfomodel.codes = codes;
    }
}
#pragma mark - addItems
-(void)addItems
{
    UIButton * cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancleBtn.frame = CGRectMake(0, 0, 60, 30);
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn addTarget:self action:@selector(backItem:) forControlEvents:UIControlEventTouchUpInside];
    [cancleBtn setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc]initWithCustomView:cancleBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
}
-(void)addRight
{
    sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame = CGRectMake(0, 0, 60, 30);
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendContentAction:) forControlEvents:UIControlEventTouchUpInside];
    [sendBtn setTitleColor:UIColorFromRGB(0x6ec844) forState:UIControlStateNormal];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:sendBtn];
    self.navigationItem.rightBarButtonItem = rightItem;

}
#pragma mark  //发送点击事件
-(void)sendContentAction:(UIButton *)btn
{
    UITextView * textView = (UITextView *)[self.view viewWithTag:712];

    if ([self isEmpty:textView.text] && myPictureArr.count == 0) {
        textView.text = @"";
        return ;
    }
    
    NSString * emjStr = textView.text;
    [emjStr enumerateSubstringsInRange:NSMakeRange(0, emjStr.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
        if (substring.length == 2) {
            NSLog(@"******%@",substring);
            [Singleton alerSendMessage:@"暂不支持表情符号"];
            return ;
        }
    }];
    
    if ([self isLogin]) {
        UIView * view = (UIView *)[self.view viewWithTag:557];
        if (view) {
            if (view.hidden == NO) {
                view.hidden = YES;
                _picAlumeTableView.hidden = YES;
                return;
            }
        }
        
        if (myPictureArr.count!=0) {
            
            [self sendPictureData];
        }
        else
        {
            [self distubteInformation];
        }
    }
    
}
-(BOOL)isLogin
{
    if ([Singleton share].code) {
        NSLog(@"登录了");
        return YES;
        
    }
    else
    {
        //        NSLog(@"还没登录呢");
        //        LoginViewController * loginVC = [[LoginViewController alloc]init];
        //        [self.navigationController pushViewController:loginVC animated:NO];
        //        return NO;
        if (SYSTEM_VERSION >= 8.0) {
            UIAlertController * alerVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录是否登录" preferredStyle:UIAlertControllerStyleAlert];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                LoginViewController * loginVC = [[LoginViewController alloc]init];
                UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginVC];
                nvc.navigationBarHidden = YES;
                
                [self presentViewController:nvc animated:YES completion:nil];
                
            }]];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }]];
            [self.view.window.rootViewController presentViewController:alerVC animated:YES completion:nil];
            
        }
        else
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有登录是否登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
        return NO;
        
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = (int)buttonIndex;
    if (i == 0) {
        
    }
    else if(i == 1)
    {
        LoginViewController * loginVC = [[LoginViewController alloc]init];
        UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginVC];
        nvc.navigationBarHidden = YES;
        [self presentViewController:nvc animated:YES completion:nil];
    }
}
-(BOOL) isEmpty:(NSString *) str {
    
    if (!str) {
        return true;
    } else {
        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

#pragma mark - NAVgationBarTitle

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UITextView * textView = (UITextView *)[self.view viewWithTag:712];
    [textView resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
